const {
	Service
} = require('uni-cloud-router')
const db = uniCloud.database()
const dbCmd = db.command
const moment = require('moment-timezone');
const dbHelper = require('db-helper')
const WxPubApi = require("wx-public-api")
const wxPubApi = new WxPubApi()

module.exports = class EnterApplyService extends Service {
	// 查询商家入驻信息
	async querySettledInfo(data) {
		const coll = db.collection("t3ds-enter-apply")
		let res = await coll.where(data).get()
		return res
	}

	// 商家入驻
	async enterApply(data) {
		console.log(data);
		const coll = db.collection("t3ds-enter-apply")
		let countRes = await coll.where({
			uid: this.ctx.auth.uid
		}).count()
		if (countRes.total) {
			throw new Error("您已提交，不能重复提交！")
		}
		try {
			data.uid = this.ctx.auth.uid
			let res = await coll.add(data)
			console.log('商家id: ' + res.id);
			if (res.id) {
				// 超管 区管
				// let admins = await dbHelper.getList("uni-id-users", {
				// 	role: dbCmd.eq('admin').or(dbCmd.eq("region_mgr")),
				// 	city: merchant.city
				// })
				let admins = []
				admins = await dbHelper.getList("uni-id-users", {
					role: dbCmd.eq("region_mgr"),
					city: data.region.city.value
				})
				if (admins.length == 0) {
					admins = await dbHelper.getList("uni-id-users", {
						role: dbCmd.eq("admin"),
						city: data.region.city.value
					})
				}
				console.log(admins);
				if (admins.length != 0) {
					for (let item of admins) {
						if (item.merchant_info && item.merchant_info.wx_unionid) {
							let wxPubUser = await dbHelper.getOne("t3ds-wx-pub-user", {
								unionId: item.merchant_info.wx_unionid,
								city: data.region.city.value
							})
							if (wxPubUser) {
								let temp = await dbHelper.getOne('t3ds-region', {'city.value': data.region.city.value})
								console.log(temp.templateMsgs);
								let tempId = temp.templateMsgs.find(item => {
									return item.templateName === '商家入驻通知'
								}).templateID
								await wxPubApi.sendTemplateMsg(data.region.city.value, {
									touser: wxPubUser.openId,
									template_id: tempId,
									miniprogram: {
										appid: "wxa7e5444036dea6af",
										pagepath: `pagesAdmin/platform/enter-apply/list`
									},
									data: {
										first: {
											value: '商家入驻通知'
										},
										keyword1: {
											value: data.storeName
										},
										keyword2: {
											value: data.name
										},
										keyword3: {
											value: moment().tz("Asia/Shanghai").format("YYYY-MM-DD HH:mm:ss")
										},
										keyword4: {
											value: '待联系'
										},
										keyword5: {
											value: '请尽快联系该商家'
										},
									}
								})
							} else {
								console.log('获取公众号失败');
							}
						} else {
							console.warn('管理员未绑定微信，无法发送通知，管理员id：', item.id)
						}
					}
				} else {
					console.log('该入驻商家所在区域无任何管理员');
				}
			} else {
				console.log('商家id不存在：' + res);
			}
		} catch (e) {
			throw e
		}
	}
}
